/// <reference path="../../js/devextreme/ts/jquery.d.ts" />

($ => {
    $.fn.diagnosisTemplateWrapper = function (options) {
        options = options || {};

        const handleLoadTemplates = (enableFilter) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-templates?templateType=${options.type}&reportId=${options.reportId}&enableFilter=${enableFilter}`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        resolve([]);
                    },
                });
            });
        };

        const handleNewTemplate = (template, parentDirectory) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/new-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({ ...template, parentId: parentDirectory?.id, reportId: options.reportId, type: options.type }),
                    success: result => {
                        resolve(result.data);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleNewTemplateBefore = () => {
            return new Promise(resolve => {
                let template = {};
                if (options.onNewTemplate) {
                    template = options.onNewTemplate(template);
                }
                resolve(template);
            });
        };

        const handleNewTemplateDirectory = (templateDirectory, parentDirectory) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/new-template-directory`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({ ...templateDirectory, parentId: parentDirectory?.id, reportId: options.reportId, type: options.type }),
                    success: result => {
                        resolve(result.data);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleUpdateTemplate = template => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/update-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify(template),
                    success: result => {
                        resolve(result.data);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleUpdateTemplateDirectory = templateDirectory => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/update-template-directory`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify(templateDirectory),
                    success: result => {
                        resolve(result.data);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleDeleteTemplate = template => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/delete-template?id=${template.templateId}&historyId=${template.historyId ? template.historyId : ''}&type=${options.type}`,
                    type: 'DELETE',
                    success: result => {
                        resolve(result);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleGetFullTemplate = template => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-full-template?id=${template?.templateId}`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        resolve({});
                    },
                });
            });
        };

        const handleTemplateDragged = e => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/sort-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({
                        fromId: e.from.id,
                        toId: e.to?.id,
                        fromIndex: e.fromIndex,
                        toIndex: e.toIndex,
                        isInside: e.isDropInsideItem
                    }),
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        reject();
                    },
                });
            });
        };

        const handleGetUserTemplateDirectories = () => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-template-directories?type=user&reportId=${options.reportId}`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        resolve([]);
                    },
                });
            });
        };

        const handleCloneToUserTemplate = (template, templateDirectoryId) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/clone-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({
                        templateId: template.id,
                        templateDirectoryId,
                        type: 'user',
                    }),
                    success: result => {
                        if (options.onRefreshTemplate) {
                            options.onRefreshTemplate('user');
                        }
                        resolve(result.data);
                    },
                    error: () => {
                        reject();
                    },
                });
            });
        };

        const handleGetDepartmentTemplateDirectories = () => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-template-directories?type=department&reportId=${options.reportId}`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        resolve([]);
                    },
                });
            });
        };

        const handleCloneToDepartmentTemplate = (template, templateDirectoryId) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/clone-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({
                        templateId: template.id,
                        templateDirectoryId,
                        type: 'department',
                    }),
                    success: result => {
                        if (options.onRefreshTemplate) {
                            options.onRefreshTemplate('department');
                        }
                        resolve(result.data);
                    },
                    error: () => {
                        reject();
                    },
                });
            });
        };

        const handleGetPublicTemplateDirectories = () => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-template-directories?type=public&reportId=${options.reportId}`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        resolve(result.data);
                    },
                    error: () => {
                        resolve([]);
                    },
                });
            });
        };

        const handleCloneToPublicTemplate = (template, templateDirectoryId) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/clone-template`,
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({
                        templateId: template.id,
                        templateDirectoryId,
                        type: 'public',
                    }),
                    success: result => {
                        if (options.onRefreshTemplate) {
                            options.onRefreshTemplate('public');
                        }
                        resolve(result.data);
                    },
                    error: () => {
                        reject();
                    },
                });
            });
        };

        const applyTemplate = (template) => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/apply-template/${template.id}`,
                    type: 'POST',
                    success: result => {
                        resolve(result);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const handleReplaceTemplate = template => {
            if (options.replaceTemplate && template?.id) {
                options.replaceTemplate(template);
                applyTemplate(template);
            }
        };

        const handleAppendTemplate = template => {
            if (options.appendTemplate && template?.id) {
                options.appendTemplate(template);
                applyTemplate(template);
            }
        };

        const handleSaveTemplate = () => {
            return new Promise(resolve => {
                let template = diagnosisTemplate.getSelectedTemplate();
                if (template) {
                    if (template.imageSeeing || template.imageDiagnosis || template.imageOpinion) {
                        if (options.saveTemplate) {
                            template = options.saveTemplate(template);
                        }
                        handleUpdateTemplate(template).then(result => {
                            resolve({ ...result, ...template });
                        });
                    }
                }
            });
        };

        const handleGetTemplate = template => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/get-template/${template.id}`,
                    type: 'GET',
                    success: result => {
                        resolve(result.data);
                    },
                    error: (error) => {
                        console.error(error);
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                });
            });
        };

        const diagnosisTemplate = $(this[0]).diagnosisTemplate({
            allowNew: true,
            allowEdit: true,
            allowDelete: true,
            allowFilter: true,
            allowCollapse: true,
            allowClone: true,
            allowCloneToUser: true,
            allowCloneToDepartment: true,
            allowCloneToPublic: true,
            onLoadTemplates: handleLoadTemplates,
            onNewTemplate: handleNewTemplate,
            onNewTemplateBefore: handleNewTemplateBefore,
            onNewTemplateDirectory: handleNewTemplateDirectory,
            onEditTemplate: handleUpdateTemplate,
            onEditTemplateDirectory: handleUpdateTemplateDirectory,
            onDeleteTemplate: handleDeleteTemplate,
            onGetFullTemplate: handleGetFullTemplate,
            onTemplateDragged: handleTemplateDragged,
            onGetUserTemplateDirectories: handleGetUserTemplateDirectories,
            onCloneToUserTemplate: handleCloneToUserTemplate,
            onGetDepartmentTemplateDirectories: handleGetDepartmentTemplateDirectories,
            onCloneToDepartmentTemplate: handleCloneToDepartmentTemplate,
            onGetPublicTemplateDirectories: handleGetPublicTemplateDirectories,
            onCloneToPublicTemplate: handleCloneToPublicTemplate,
            onReplaceTemplate: handleReplaceTemplate,
            onAppendTemplate: handleAppendTemplate,
            onSaveTemplate: handleSaveTemplate,
            onGetTemplate: handleGetTemplate,
            ...options,
        });

        return diagnosisTemplate;
    };
})(jQuery);
